"use strict"

const mysql = require('mysql2/promise')
const config = require('../config')
const _ = require('lodash/fp')


const create_table_sql = table_name =>
    `CREATE TABLE \`${table_name}\` (
        \`id\` CHAR (50),
        \`live_id\` INT (10) UNSIGNED NOT NULL,
        \`name\` CHAR (255) NOT NULL,
        \`room_name\` CHAR (255) NOT NULL,
        \`room_id\` CHAR (50) NOT NULL,
        \`url\` CHAR (255)  NOT NULL,
        \`cover\` CHAR (255)  NOT NULL,
        \`avatar\` CHAR (255)  NOT NULL,
        \`online\` INT (10) UNSIGNED NOT NULL,
        \`category_id\` CHAR (20)  NOT NULL,
        \`status\` TINYINT (4) NOT NULL DEFAULT '0',
        PRIMARY KEY (\`id\`),
        KEY \`name\` (\`name\`(250)),
        KEY \`room_name\` (\`room_name\`(250)),
        KEY \`online\` (\`online\`),
        KEY \`status\` (\`status\`)
    ) ENGINE = INNODB DEFAULT CHARSET = utf8mb4;`

const store = async data => {
    const db = await mysql.createConnection(config.DB)

    //1.create new table for online anchors
    const table_name = `qyg_online_anchors_${new Date().getTime()}`
    await db.query(create_table_sql(table_name))

    const insert_sql = `INSERT INTO ${table_name} (${config.cols.join(',')},status) VALUES ${
        data.map(row => `(${config.cols.map(col => `'${row[col]}'`).join(',')},1)`).join(',')
    }`

    await db.query(insert_sql)

    await db.query(`UPDATE qyg_anchor_cnf SET \`value\` = '${table_name}' WHERE \`key\` = 'current_anchor_table'`)

    return db.end()
}

module.exports = store